package com.xhs.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @desc: 下载文件工具类
 * @projectName: tools-parent
 * @author: xhs
 * @date: 2022/12/3 22:02
 * @version: JDK 1.8
 */
@Slf4j
public class DownloadUtil {
    /**
     * 根据url从服务器下载文件到指定位置
     *
     * @param urlStr   文件url地址
     * @param fileName 文件名称
     * @param filePath 文件保存地址
     * @param fileSize 文件大小
     * @return 文件路径
     * @throws IOException
     */
    public static String downLoadFromUrl(String urlStr, String fileName, String filePath, int fileSize) throws IOException {
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //设置超时间为3秒
        conn.setConnectTimeout(3 * 1000);
        //防止屏蔽程序抓取而返回403错误
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        //得到输入流
        InputStream inputStream = conn.getInputStream();
        //获取字节数组
        byte[] getData = readInputStream(inputStream);
        //文件保存位置
        File saveDir = new File(filePath);
        long size = saveDir.length();
        // 判断文件大小
        if (size > fileSize * 1024 * 1024) {
            return null;
        }
        // 创建文件
        if (!saveDir.exists()) {
            saveDir.mkdir();
        }
        String path;
        if (!StringUtils.isEmpty(fileName)) {
            path = saveDir + File.separator + fileName;
        } else {
            path = saveDir + File.separator;
        }
        log.info(">>>>>>>>>>>>【downLoadFromUrl】-文件路径：{}<<<<<<<<<<<<<<<", path);
        File file = new File(path);
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(getData);
        if (fos != null) {
            fos.close();
        }
        if (inputStream != null) {
            inputStream.close();
        }
        return path;
    }

    /**
     * 从输入流中获取字节数组
     *
     * @param inputStream inputStream
     * @throws IOException
     */
    public static byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }
}
